@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul
echo ========================================
echo    Feng Admin Project Startup Script
echo ========================================
echo.

REM 跳转到函数后面
goto :main

REM ===== 函数: 快速配置 =====
:quick_setup
echo.
echo ========================================
echo    Quick Environment Setup
echo ========================================
echo.

REM 生成密钥
echo Generating security keys...
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))" 2^>nul') do set SECRET_KEY=%%i
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))" 2^>nul') do set JWT_SECRET_KEY=%%i

REM 如果Python命令失败，使用备用方法
if "!SECRET_KEY!"=="" (
    set SECRET_KEY=dev-secret-key-%RANDOM%%RANDOM%
    set JWT_SECRET_KEY=jwt-secret-key-%RANDOM%%RANDOM%
)

REM 询问是否远程访问
set /p remote_access="Do you need remote access configuration? (y/N): "

if /i "!remote_access!"=="y" (
    echo.
    echo Enter server domain or IP ^(e.g., yourwebsite.net or 192.168.1.100^)
    set /p server_addr="Domain/IP: "
    
    echo.
    set /p frontend_port="Frontend port (Enter for 5173): "
    if "!frontend_port!"=="" set frontend_port=5173
    
    echo.
    set /p backend_port="Backend port (Enter for 5001): "
    if "!backend_port!"=="" set backend_port=5001
    
    echo.
    echo Choose protocol:
    echo   1. HTTP
    echo   2. HTTPS
    set /p protocol_choice="Choose (1-2) [1]: "
    if "!protocol_choice!"=="2" (
        set protocol=https
    ) else (
        set protocol=http
    )
    
    set API_URL=!protocol!://!server_addr!:!backend_port!/api
    set CORS_ORIGIN=!protocol!://!server_addr!:!frontend_port!
) else (
    set backend_port=5001
    set frontend_port=5173
    set API_URL=http://localhost:!backend_port!/api
    set CORS_ORIGIN=http://localhost:!frontend_port!
)

REM 创建后端 .env 文件
echo # Feng Admin Backend Configuration> apps\backend\.env
echo # Quick setup generated on %date% %time%>> apps\backend\.env
echo.>> apps\backend\.env
echo FLASK_ENV=development>> apps\backend\.env
echo FLASK_DEBUG=True>> apps\backend\.env
echo SECRET_KEY=!SECRET_KEY!>> apps\backend\.env
echo JWT_SECRET_KEY=!JWT_SECRET_KEY!>> apps\backend\.env
echo JWT_ACCESS_TOKEN_EXPIRES=24>> apps\backend\.env
echo JWT_REFRESH_TOKEN_EXPIRES=30>> apps\backend\.env
echo CORS_ORIGINS=!CORS_ORIGIN!>> apps\backend\.env
echo GITHUB_TRENDING_CACHE_HOURS=4>> apps\backend\.env
echo LOG_LEVEL=INFO>> apps\backend\.env
echo FLASK_HOST=0.0.0.0>> apps\backend\.env
echo FLASK_PORT=!backend_port!>> apps\backend\.env

echo Backend configuration created

REM 创建前端 .env 文件
echo # Feng Admin Frontend Configuration> apps\frontend\.env
echo # Quick setup generated on %date% %time%>> apps\frontend\.env
echo.>> apps\frontend\.env
echo VITE_API_BASE_URL=!API_URL!>> apps\frontend\.env
echo VITE_APP_TITLE=Feng Admin>> apps\frontend\.env
echo VITE_APP_VERSION=1.0.0>> apps\frontend\.env
echo VITE_ENABLE_DEV_TOOLS=true>> apps\frontend\.env
echo VITE_ENABLE_LOGGING=true>> apps\frontend\.env
echo VITE_SERVER_HOST=0.0.0.0>> apps\frontend\.env
echo VITE_SERVER_PORT=!frontend_port!>> apps\frontend\.env

echo Frontend configuration created

echo.
echo ========================================
echo    Configuration completed!
echo ========================================
if /i "!remote_access!"=="y" (
    echo.
    echo Configuration Info:
    echo   Frontend: !CORS_ORIGIN!
    echo   Backend:  !API_URL!
)
echo.
goto :eof

REM ===== 主程序开始 =====
:main

echo [1/4] Checking Node.js environment...
node --version >nul 2>&1
if %errorlevel% neq 0 (
    echo Error: Node.js not found, please install Node.js first
    pause
    exit /b 1
)
echo Node.js environment is OK

echo.
echo [2/4] Checking Python virtual environment...
if not exist ".venv\Scripts\python.exe" (
    echo Virtual environment not found, creating...
    python -m venv .venv
    if %errorlevel% neq 0 (
        echo Error: Failed to create virtual environment
        echo Please ensure Python is installed correctly
        pause
        exit /b 1
    )
    echo Virtual environment created successfully
) else (
    echo Virtual environment already exists
)

echo.
echo [3/5] Checking environment configuration...

REM 检查后端 .env 文件
if not exist "apps\backend\.env" (
    echo.
    echo WARNING: Backend .env file not found
    echo.
    echo Please choose configuration method:
    echo   1. Quick setup ^(recommended^)
    echo   2. Skip ^(use default settings^)
    echo.
    set /p config_choice="Choose (1-2) [1]: "
    if "!config_choice!"=="" set config_choice=1
    
    if "!config_choice!"=="1" (
        call :quick_setup
    ) else (
        echo Using default configuration...
    )
) else (
    echo Backend configuration found
)

REM 检查前端 .env 文件
if not exist "apps\frontend\.env" (
    echo WARNING: Frontend .env file not found ^(optional^)
) else (
    echo Frontend configuration found
)

echo.
echo [4/5] Installing dependencies...
echo Installing frontend dependencies...
call npm run install:frontend
if %errorlevel% neq 0 (
    echo Error: Frontend dependencies installation failed
    pause
    exit /b 1
)

echo Installing backend dependencies...
echo Installing Python dependencies in virtual environment...
call .venv\Scripts\pip.exe install -r apps\backend\requirements.txt
if %errorlevel% neq 0 (
    echo Error: Backend dependencies installation failed
    pause
    exit /b 1
)

echo.
echo [5/5] Starting services...
echo Dependencies installation completed
echo.
echo Starting backend service...
start "Feng Admin Backend" cmd /k ".\.venv\Scripts\python.exe apps\backend\app.py"

echo Waiting for backend service to start...
timeout /t 3 /nobreak >nul

echo Starting frontend service...
start "Feng Admin Frontend" cmd /k "npm run dev"

echo.
echo ========================================
echo Startup completed successfully!
echo ========================================
echo.
echo Note: Actual ports may differ if configured in .env files
echo Check the service windows for actual access URLs
echo.
echo Default Access:
echo   Frontend: http://localhost:5173
echo   Backend:  http://localhost:5001/api
echo.
echo Remote Access:
echo   Frontend: http://YOUR_IP:5173
echo   Backend:  http://YOUR_IP:5001/api
echo   (Replace YOUR_IP with your server IP address, use 'ipconfig' to check)
echo.
echo Tips:
echo   - Frontend and backend services are running in new windows
echo   - Closing this window will not affect the services
echo   - To stop services, close the corresponding service windows
echo   - For remote access guide, see docs\REMOTE_ACCESS_GUIDE.md
echo.
echo Press any key to exit...
pause >nul
